<template>
  <a-select
    style="width: 100%"
    :mode="multiple"
    show-search
    v-model="realnames"
    :default-active-first-option="false"
    :show-arrow="false"
    :filter-option="false"
    :not-found-content="null"
    @search="fetchUserList"
    :disabled="disabled"
    @focus="selectLimtUser"
    @change="selectUserList"
    allowClear
    :placeholder="(placeholder ? placeholder : '请输入账号或名称查询') + (multiple == 'multiple' ? ',可多选' : ',单选')"
  >
    <a-select-option v-for="(d, index) in personList" :value="d[codeKey]" :key="index + d.randomStr">
      {{ d[nameKey] }}({{ d[codeKey] }})
    </a-select-option>
  </a-select>
</template>
<script>
import { postAction } from '@/api/manage'
export default {
  name: 'UserSelector',
  props: {
    username: {
      type: String,
      default: '',
    },
    realname: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    multiple: {
      type: String,
      default: "default",
    },
    nameKey: {
      type: String,
      default: 'realname',
    },
    codeKey: {
      type: String,
      default: 'username',
    },
    limit: {
      type: Array,
      default: () => [],
    },
    placeholder: {
      type: String,
      default: '请输入账号或名称查询',
    },
    selectedReturn: {
      type: String,
      default: '0',
    },
  },
  emits: [
    // 写法与绑定单个值一样   只不过也是父组件绑定多少个就写多少个
    'update:username',
    'update:realname',
  ],
  computed: {
    realnames: {
      get() {
        if (this.multiple == 'multiple') {
          if (this.realname) {
            let temp = []
            let realnamearrs = this.realname.split(',')
            let usernamearrs = this.username?this.username.split(','):[]
            for(let i in realnamearrs)(
              temp.push(realnamearrs[i]+"("+usernamearrs[i]+")")
            )
            return temp
          } else {
            return []
          }
        } else {
          return this.realname ? this.realname+"("+this.username+")":undefined
        }
      },
      set(value) {
        if (Array.isArray(value)) {
          this.$emit('update:realname', value.join(','))
        } else {
          this.$emit('update:realname', value)
        }
      },
    },
    usernames: {
      get() {
        if (this.multiple == 'multiple') {
          if (this.username) {
            return this.username.split(',')
          } else {
            return []
          }
        } else {
          return this.username
        }
      },
      set(value) {
        if (Array.isArray(value)) {
          this.$emit('update:username', value.join(','))
        } else {
          this.$emit('update:username', value)
        }
      },
    },
    userMap() {
      let map = {}
      if (this.usernames && this.realname) {
        let usernames = this.username.split(',')
        let realnames = this.realname.split(',')
        for (let i = 0; i < realnames.length; i++) {
          map[usernames[i]] = realnames[i]
        }
      }
      return map
    },
    nameMap() {
      let map = {}
      if (this.usernames && this.realname) {
        let usernames = this.username.split(',')
        let realnames = this.realname.split(',')
        for (let i = 0; i < realnames.length; i++) {
          map[realnames[i]] = usernames[i]
        }
      }
      return map
    },
  },
  data() {
    return {
      urls: {
        personList: '/person/info/personList',
        personListByUserNames: '/person/info/personListByUserNames',
      },
      personMap: [],
      realNameMap: [],
      personList: [],
      selectUserTimeOut: null,
      selectUserKeyWord: null
    }
  },
  methods: {
    selectLimtUser() {
      if (this.limit && this.limit.length > 0) {
        this.personMap = []
        this.personList = this.limit
        this.limit.forEach((p) => {
          p.randomStr = this.getRandomStr(10)
          this.$set(this.personMap, p[this.codeKey], p)
        })
      }
    },
    fetchUserList(value) {
      if (!value || (this.limit && this.limit.length > 0)) {
        return
      }
      if (this.selectUserTimeOut) {
        window.clearTimeout(this.selectUserTimeOut)
      }
      this.selectUserTimeOut = window.setTimeout(this.toFetchUserList, 800)
      this.selectUserKeyWord = value
    },

   async personListByUserNames(userNames) {
      if(this.selectedReturn == 1){
        let res = await postAction(this.urls.personListByUserNames, userNames)
        if(res.success){
          this.$emit("selected",res.result)
        }
      }
      
    },
    
    async toFetchUserList() {
      let param = {}
      param.keyword = this.selectUserKeyWord
      param.pageSize = 10
      this.personMap = []
      this.personList = []
      let res = await postAction(this.urls.personList, param)
      if (res.success) {
        let list = res.result.records
        list.forEach((p) => {
          p.randomStr = this.getRandomStr(10)
          if (!this.personMap[p[this.codeKey]]) {
            this.$set(this.personMap, p[this.codeKey], p)
            this.personList.push(p)
          }
        })
        this.$forceUpdate()
      }
    },
    selectUserList(selected) {
      let usernames = []
      let realnames = []
      if (this.multiple == 'multiple') {
        selected.forEach((s0) => {
          let s  = s0
          if(s.indexOf("(")>-1){
            s = s.substring(0,s.indexOf("("))
          }
          if (usernames.indexOf(s) < 0) {
            if (this.personMap[s]) {
              usernames.push(s)
              realnames.push(this.personMap[s][this.nameKey])
            } else if (this.userMap[s]) {
              usernames.push(s)
              realnames.push(this.userMap[s])
            } else if (this.nameMap[s]) {
              usernames.push(this.nameMap[s])
              realnames.push(s)
            }
          }
        })
      } else {
        let s  = selected
          if(s && s.indexOf("(")>-1){
            s = s.substring(0,s.indexOf("("))
          }
        if (this.personMap[s]) {
          usernames.push(s)
          realnames.push(this.personMap[s][this.nameKey])
        } else if (this.userMap[s]) {
          usernames.push(s)
          realnames.push(this.userMap[s])
        } else if (this.nameMap[s]) {
          usernames.push(this.nameMap[s])
          realnames.push(s)
        }
      }
      this.$emit('update:username', usernames.join(','))
      this.$emit('update:realname', realnames.join(','))
      this.personListByUserNames(usernames)
    },
    getRandomStr(len) {
      len = len || 32
      var $chars =
        'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      var maxPos = $chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
  },
}
</script>
